<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="20">
        <el-col :span="24" align="right">
          <el-form-item label="发货单号" prop="fhCode">
            <el-input
              v-model="queryParams.fhCode"
              placeholder="请输入发货单号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['warehouse:cpfh:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['warehouse:cpfh:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['warehouse:cpfh:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!--        <el-button-->
        <!--          type="warning"-->
        <!--          plain-->
        <!--          icon="el-icon-download"-->
        <!--          size="mini"-->
        <!--          @click="handleExport"-->
        <!--          v-hasPermi="['warehouse:cpfh:export']"-->
        <!--        >导出</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cpfhList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发货单号" align="center" prop="fhCode" width="180" />
      <el-table-column label="收货客户" align="center" prop="ksMerchants.merchantsName" />
      <el-table-column label="产品编码" align="center" prop="cpCode" width="180" />
      <el-table-column label="产品名称" align="center" prop="cpProduct.cpName" />
      <el-table-column label="产品类型" align="center" prop="cpProduct.cpLxcode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_type" :value="scope.row.cpProduct.cpLxcode"/>
        </template>
      </el-table-column>
      <el-table-column label="产品型号" align="center" prop="cpProduct.cpType" />
      <el-table-column label="产品分类" align="center" prop="cpProduct.cpflProductClassification.cpflName" />
      <el-table-column label="产品品牌" align="center" prop="cpProduct.cpppProductBrand.ppName" />
      <el-table-column label=发货数量 align="center" prop="fhNum" />
      <el-table-column label="发货人" align="center" prop="fhPeo" />
      <el-table-column label="发货时间" align="center" prop="fhTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fhTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleExamine(scope.row)"
            v-hasPermi="['warehouse:llrk:examine']"
            v-if="scope.row.isExamine===1"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouse:cpfh:edit']"
            v-if="scope.row.isExamine===1"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['warehouse:cpfh:remove']"
            v-if="scope.row.isExamine===1"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetails(scope.row)"
            v-hasPermi="['warehouse:llrk:submit']"
            v-if="scope.row.isExamine===0"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleCancel(scope.row)"
            v-if="scope.row.isExamine===0"
          >撤销</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改成品发货对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-form-item label="产品名称" prop="cpCode">
          <el-input v-model="form.cpProduct.cpName" placeholder="请选择产品" readonly
                    @click.native="selectProduct()" suffix-icon="el-icon-more"/>
        </el-form-item>
        <el-form-item label="产品型号" prop="cpType">
          <el-input v-model="form.cpProduct.cpType" placeholder="请选择产品" style="width: 220px" readonly/>
        </el-form-item>
        <el-form-item label="发货时间" prop="fhTime">
          <el-date-picker clearable
                          v-model="form.fhTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客商名称" prop="ksCode">
          <el-input v-model="form.ksMerchants.merchantsName" placeholder="请选择客商" readonly
                    @click.native="selectMerchants()" suffix-icon="el-icon-more"/>
        </el-form-item>

        <el-divider content-position="center">发货数量信息</el-divider>
        <el-table :data="form.cpkcList" :row-class-name="rowFhslQuantityShippedIndex" @selection-change="handleFhslQuantityShippedSelectionChange" ref="fhslQuantityShipped">
          <el-table-column type="selection" width="50" />
          <el-table-column label="序号" prop="index" width="50"/>
          <el-table-column label="发货仓库" prop="ckWarehouse.ckName"/>
          <el-table-column label="产品批次" prop="cppcCode" />
          <el-table-column label="库存数量" prop="havenum" />
          <el-table-column label="发货数量" prop="fhNum" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.fhslQuantityShipped.fhNum" placeholder="请输入发货数量" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="PopUpsTitle" :visible.sync="open1" width="40%">
      <el-container>
        <el-header>
          <el-input suffix-icon="el-icon-search" v-model="queryParams1.merchantsName" @keyup.enter.native="peoUpsQuery"></el-input>
        </el-header>
        <!--展示客商信息-->
        <el-main v-if="ksOpen" v-loading="loading1">
          <el-table border :data="ksMerchantsList" @row-click="ksHandleRowClick">
            <el-table-column prop="ksCode" label="客商编号" width="140px"></el-table-column>
            <el-table-column prop="merchantsName" label="客商名称"></el-table-column>
            <el-table-column prop="ksLevelCode" label="客商等级"></el-table-column>
          </el-table>
        </el-main>
        <!--展示产品信息-->
        <el-main v-if="cpOpen" v-loading="loading1">
          <el-table border :data="ProductList" @row-click="ProductRowClick">
            <el-table-column prop="cpCode" label="产品编号" width="140px"></el-table-column>
            <el-table-column prop="cpName" label="产品名称"></el-table-column>
            <el-table-column prop="cpTypecode" label="产品分类"></el-table-column>
            <el-table-column prop="cpType" label="产品型号"></el-table-column>
          </el-table>
        </el-main>
        <pagination
          v-show="queryParams1.total>0"
          :total="queryParams1.total"
          :page.sync="queryParams1.pageNum"
          :limit.sync="queryParams1.pageSize"
          @pagination="selectMerchants"
        />
      </el-container>
    </el-dialog>


    <!--  详情弹窗  -->
    <el-dialog title="入库详情" :visible.sync="open2" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px" style="font-size: 10px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称：" prop="cpProduct.cpName">
              <span>{{ form.cpProduct.cpName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品型号：" prop="cpProduct.cpType">
              <span>{{ form.cpProduct.cpType }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发货时间：" prop="fhTime">
              <span>{{ form.fhTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客商名称：" prop="wldaMaterialFile.wlGg">
              <span>{{ form.ksMerchants.merchantsName }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">出库详情</el-divider>
        <el-table :data="form.cpkcList" :row-class-name="rowFhslQuantityShippedIndex" @selection-change="handleFhslQuantityShippedSelectionChange" ref="fhslQuantityShipped">
          <el-table-column type="selection" width="50" />
          <el-table-column label="序号" prop="index" width="50"/>
          <el-table-column label="发货仓库" prop="ckWarehouse.ckName"/>
          <el-table-column label="产品批次" prop="cppcCode" />
          <el-table-column label="发货数量" prop="fhslQuantityShipped.fhNum" >
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="clickOpen2">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCpfh, getCpfh, delCpfh, addCpfh, updateCpfh, getCpfhTj, examine, cancel} from "@/api/warehouse/cpfh";
import {listMerchants} from "@/api/jbxx/merchants";
import {listProduct} from "@/api/jbxx/product";

export default {
  name: "Cpfh",
  dicts: ['wl_from', 'is_use', 'wl_type', 'wl_sortcode','product_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loading1:true,
      // 选中数组
      ids: [],
      ids1: [],
      // 子表选中数据
      checkedFhslQuantityShipped: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成品发货表格数据
      cpfhList: [],
      // ${subTable.functionName}表格数据
      ksMerchantsList:[],
      ksOpen:false,

      ProductList:[],
      cpOpen:false,
      // 弹出层标题
      title: "",
      // 弹出层标题
      PopUpsTitle: null,
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（添加参数选择）
      open1: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fhCode: null,
      },
      // 查询弹窗2参数
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        cpName: null,
        merchantsName:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cpCode: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        fhTime: [
          { required: true, message: "发货时间不能为空", trigger: "blur" }
        ],
        ksCode: [
          { required: true, message: "客商不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询成品发货列表 */
    getList() {
      this.reset()
      this.loading = true;
      listCpfh(this.queryParams).then(response => {
        this.cpfhList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fhCode: null,
        cpCode: null,
        ksCode: null,
        fhPeo: null,
        fhTime: null,
        cpProduct: {
          cpName:null,
          cpType:null
        },
        ksMerchants:{
          merchantsName:null
        },
        cpkcList:[]
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fhCode)
      this.ids1 = selection.map(item => item.cpCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加成品发货";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fhCode = row.fhCode
      getCpfh(fhCode).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改成品发货";
      });
    },
    /** 详情 */
    handleDetails(row){
      const fhCode = row.fhCode
      getCpfh(fhCode).then(response => {
        this.form = response.data;
        this.open2 = true;
      });
    },
    clickOpen2(){
      this.open2=false
    },
    /** 撤销 */
    handleCancel(row){
      const fhCode = row.fhCode
      this.$modal.confirm('是否撤销产品发货编号为"' + fhCode + '"的数据项？').then(function () {
        return cancel(fhCode);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤销成功");
      }).catch(() => {
      });
    },
    /** 审核 */
    handleExamine(row){
      const fhCodes = row.fhCode;
      this.$modal.confirm('是否确认审批产品发货编号为"' + fhCodes + '"的数据项？').then(function () {
        return examine(fhCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("审批成功");
      }).catch(() => {
      });
    },
    PopUpsShow() {
      this.open1 = true
      this.loading1=true
      this.ksOpen=false
      this.cpOpen=false
    },
    /**
     * 选择客商
     * */
    selectMerchants() {
      this.PopUpsShow()
      this.ksOpen=true
      this.PopUpsTitle = "选择客商";
      listMerchants(this.queryParams1).then(response => {
        this.ksMerchantsList = response.rows;
        this.loading1=false
        this.queryParams1.total = response.total;
        this.queryParams1.merchantsName=null
        this.queryParams1.cpName=null
      });
    },
    ksHandleRowClick(row){
      this.open1 = false
      this.form.ksCode=row.ksCode;
      this.form.ksMerchants.ksCode=row.ksCode;
      this.form.ksMerchants.merchantsName=row.merchantsName;
    },
    /**
     * 选择产品
     * */
    selectProduct() {
      this.PopUpsShow()
      this.cpOpen=true
      this.PopUpsTitle = "选择产品";
      listProduct(this.queryParams1).then(response => {
        this.ProductList = response.rows;
        this.loading1=false
        this.queryParams1.total = response.total;
        this.queryParams1.merchantsName=null
        this.queryParams1.cpName=null
      });
    },
    ProductRowClick(row){
      this.open1 = false
      this.form.cpCode=row.cpCode;
      this.form.cpProduct.cpName=row.cpName;
      this.form.cpProduct.cpType=row.cpType;
      getCpfhTj(this.form.cpCode).then(response => {
        if(response){
          this.form.cpkcList = response.data.cpkcList

        }
      });
    },
    peoUpsQuery(){
      this.queryParams1.cpName=this.queryParams1.merchantsName
      if(this.ksOpen){
        this.selectMerchants()
      }else if(this.cpOpen){
        this.selectProduct()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取表格长度，判断是否有添加数据
          let cpkcLength=this.form.cpkcList.length
          if(cpkcLength===0){
            this.$message.error('该产品暂无库存,无法发货');
            return;// 没有数据阻止提交
          }
          let change = 0;
          // 遍历表格数据，检查每行数据是否符合要求
          for (let i = 0; i < cpkcLength; i++) {
            const rowData = this.form.cpkcList[i];
            if (rowData.fhslQuantityShipped.fhNum && rowData.fhslQuantityShipped.fhNum!=0) {
              change = 1
            }
            if(rowData.havenum<rowData.fhslQuantityShipped.fhNum){
              change = 2
            }
          }
          if (change === 0){
            this.$message.error('请填写发货数量');
            return; // 阻止提交
          }
          if(change === 2){
            this.$message.error('发货数量不可大于库存');
            return; // 阻止提交
          }
          if (this.form.fhCode != null) {
            updateCpfh(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if(this.form.cpkcList===null){
              this.$modal.alert('该产品没有库存无法发货')
            }else {
              addCpfh(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fhCodes = row.fhCode || this.ids;
      this.$modal.confirm('是否确认删除成品发货编号为"' + fhCodes + '"的数据项？').then(function() {
        return delCpfh(fhCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** ${subTable.functionName}序号 */
    rowFhslQuantityShippedIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 复选框选中数据 */
    handleFhslQuantityShippedSelectionChange(selection) {
      this.checkedFhslQuantityShipped = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehouse/cpfh/export', {
        ...this.queryParams
      }, `cpfh_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
